<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <template #slot-left>
          <span>共19条记录</span>
        </template>
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table :data="employeesList" border :default-sort="{prop:'workNumber'}">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template slot-scope="scope">
              <!-- <img class="staffPhoto" :src="scope.row.staffPhoto"> -->
              <image-holder :img="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ scope.row.formOfEmployment|formatter }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column prop="formOfEmployment" label="账户状态" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setRoule(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[5,10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <!-- 弹框组件 -->
        <el-dialog
          title="新增员工"
          :visible.sync="showDialog"
          width="50%"
          @close="restForm"
        >
          <emp-dialog ref="addEmpRef" @close="showDialog=false" @update="updateList" />
        </el-dialog>
        <el-dialog
          title="分配角色"
          :visible.sync="showRouleDialog"
          width="50%"
        >
          <assign-role v-if="showRouleDialog" :user-id="userId" @close="showRouleDialog=false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import '@/components'
import { getEmployeeList, delEmployee } from '@/api/PageTools'
import EmployeeEnum from '@/constant/employees'
import empDialog from '@/views/employees/empDialog.vue'
import dayjs from 'dayjs'
import AssignRole from './components/assignRole.vue'
export default {
  name: 'Employees',
  filters: {
    formatter(val) {
      const res = EmployeeEnum.hireType.find(item => item.id === Number(val))
      // console.log(res)
      if (res) {
        return res.value
      } else {
        return '未知 '
      }
    },
    formatTime(time) {
      // dayjs 方法接收需要格式化的时间
      // format 方法是指按照哪种格式对时间进行格式化
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  components: {
    empDialog,
    AssignRole
  },
  // 格式化时间

  data() {
    return {
      query: {
        page: 1,
        size: 10
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 新增员工弹框显示隐藏
      showRouleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 分配员工角色
    setRoule(id) {
      this.userId = id
      this.showRouleDialog = true
    },

    // 导出Excel功能
    async downloadExcel() {
      // 获取最新数据
      const res = await getEmployeeList(this.query)
      const { header, data } = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    // 格式化后端数据
    transData(rows) {
      // 声明需要枚举的数据
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // 表头 --> ['id', 'password', .....]
      const headerArr = Object.keys(rows[0])

      const header = headerArr.map(item => {
        return map[item]
      })

      // 需要导出的具体的数据
      const data = rows.map(item => {
        return Object.values(item)
      })

      return { header, data }
    },

    // 关闭弹框，重置表单
    restForm() {
      this.$refs.addEmpRef.restForm()
    },
    // 子组件传递的close事件回调
    updateList() {
      this.showDialog = false
      this.getEmployeeList()
    },
    // 删除员工方法
    async doDel(id) {
      const res = await delEmployee(id)
      console.log(res)
      this.getEmployeeList()
      this.$message.success('删除成功')
    },
    // 用户点击删除
    delEmployee(id) {
      this.$confirm('你确定要删除员工吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.doDel(id)
      }).catch(() => {})
    },
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      this.employeesList = res.data.rows
      // console.log(res.data.rows)
      this.total = res.data.total
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },
    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    }
  }
  // components: {
  //   PageTools // 导入自定义组件
  // }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}</style>
